@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)

package com.ljj.bitetime.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.List
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.icons.filled.ShoppingCart
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.core.content.FileProvider
import androidx.core.content.edit
import coil.compose.SubcomposeAsyncImage
import coil.request.ImageRequest
import com.ljj.bitetime.R
import com.ljj.bitetime.data.MockData
import com.ljj.bitetime.item.Cart
import com.ljj.bitetime.item.Dish
import com.ljj.bitetime.item.Shop
import com.ljj.bitetime.ui.dialog.DishDetailDialog
import com.ljj.bitetime.ui.theme.BiteTimeTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.net.URL
import java.util.Locale

class ShopActivity : ComponentActivity() {
    private val context = this
    private lateinit var shop: Shop
    var cart by mutableStateOf(Cart())
    var isFavorite by mutableStateOf(false)

    val checkoutLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == RESULT_OK) {
            finish()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        shop = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            intent.getParcelableExtra("shop", Shop::class.java)
        } else {
            @Suppress("DEPRECATION")
            intent.getParcelableExtra("shop")
        })!!
        loadPreferencesState()
        setContent {
            BiteTimeTheme {
                Shop(shop = shop)
            }
        }
    }

    private fun loadPreferencesState() {
        val prefs = getSharedPreferences("shop_favorites", MODE_PRIVATE)
        isFavorite = prefs.getBoolean("favorite_${shop.id}", false)
    }

    fun saveFavoriteState() {
        val prefs = getSharedPreferences("shop_favorites", MODE_PRIVATE)
        prefs.edit {putBoolean("favorite_${shop.id}", isFavorite) }
    }

    @Composable
    fun Shop(shop: Shop) {
        val scope = rememberCoroutineScope()
        val cart = context.cart
        val scrollState = rememberScrollState()
        Box(
            modifier = Modifier.fillMaxSize()
        ) {
            Scaffold(
                modifier = Modifier
                    .fillMaxSize(),
                topBar = {
                    TopAppBar(
                        navigationIcon = {
                            IconButton(
                                onClick = { context.finish() }
                            ) {
                                Icon(
                                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                                    contentDescription = "返回"
                                )
                            }
                        },
                        actions = {
                            var isExpanded by remember { mutableStateOf(false) }
                            IconButton(
                                onClick = { isExpanded = !isExpanded }
                            ) {
                                Icon(
                                    imageVector = Icons.AutoMirrored.Filled.List,
                                    contentDescription = "更多"
                                )
                            }
                            DropdownMenu(
                                expanded = isExpanded,
                                onDismissRequest = { isExpanded = false }
                            ) {
                                DropdownMenuItem(
                                    text = { Text("分享") },
                                    onClick = {
                                        isExpanded = false
                                        scope.launch {
                                            try {
                                                // 下载图片到本地缓存
                                                val imageUri = downloadImageToCache(context, shop.imageRes)
                                                if (imageUri != null) {
                                                    // 创建分享 Intent
                                                    val sendIntent = Intent().apply {
                                                        action = Intent.ACTION_SEND
                                                        putExtra(Intent.EXTRA_STREAM, imageUri)
                                                        type = "image/*"
                                                        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                                                    }
                                                    val shareIntent = Intent.createChooser(sendIntent, "分享到")
                                                    context.startActivity(shareIntent)
                                                } else {
                                                    // 下载失败，只分享文本
                                                    val sendIntent = Intent().apply {
                                                        action = Intent.ACTION_SEND
                                                        putExtra(Intent.EXTRA_TEXT, "推荐一家好店：${shop.name}")
                                                        type = "text/plain"
                                                    }
                                                    val shareIntent = Intent.createChooser(sendIntent, "分享到")
                                                    context.startActivity(shareIntent)
                                                }
                                            } catch (e: Exception) {
                                                Toast.makeText(context, "分享失败: ${e.message}", Toast.LENGTH_SHORT).show()
                                            }
                                        }
                                    },
                                    leadingIcon = {
                                        Icon(
                                            imageVector = Icons.Filled.Share,
                                            contentDescription = "分享"
                                        )
                                    }
                                )
                                DropdownMenuItem(
                                    text = { Text("收藏") },
                                    onClick = {
                                        context.isFavorite = !context.isFavorite
                                        context.saveFavoriteState()
                                        Toast.makeText(context, if (context.isFavorite) "收藏成功" else "取消收藏", Toast.LENGTH_SHORT).show()
                                        isExpanded = false
                                    },
                                    leadingIcon = {
                                        Icon(
                                            imageVector = if (context.isFavorite) Icons.Filled.Favorite else Icons.Filled.FavoriteBorder,
                                            contentDescription = "收藏"
                                        )
                                    }
                                )
                            }
                        },
                        title = {
                            Text(
                                text = shop.name,
                                color = MaterialTheme.colorScheme.primary,
                                style = MaterialTheme.typography.titleMedium,
                                fontWeight = FontWeight.Bold,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                    )
                }
            ) { innerPadding ->
                ConstraintLayout(
                    modifier = Modifier
                        .padding(top = innerPadding.calculateTopPadding())
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.surface)
                        .verticalScroll(scrollState)
                ) {
                    val (detail, orderList) = createRefs()
                    Detail(
                        shop = shop,
                        modifier = Modifier
                            .constrainAs(detail) {
                                top.linkTo(parent.top)
                                start.linkTo(parent.start)
                                end.linkTo(parent.end)
                            }
                    )
                    OrderArea(
                        shopId = shop.id,
                        modifier = Modifier
                            .constrainAs(orderList) {
                                top.linkTo(detail.bottom)
                                start.linkTo(parent.start)
                                end.linkTo(parent.end)
                            },
                        innerPadding = innerPadding,
                        pageScrollState = scrollState
                    )
                }
            }
            if (cart.items.isNotEmpty()) {
                Box(
                    modifier = Modifier.align(Alignment.BottomCenter)
                ) {
                    CartBoard(cart = cart)
                }
            }
        }
    }

    @Composable
    fun CartBoard(cart: Cart) {
        var cartBoardWidth by remember { mutableIntStateOf(0) }
        val roundedCornerSize = 12.dp
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .shadow(
                    elevation = 4.dp,
                    shape = RoundedCornerShape(roundedCornerSize)
                )
                .clip(RoundedCornerShape(roundedCornerSize))
                .onGloballyPositioned { coordinates ->
                    cartBoardWidth = coordinates.size.width
                }
        ) {
            var showCartPopup by remember { mutableStateOf(false) }
            ConstraintLayout(
                modifier = Modifier
                    .background(MaterialTheme.colorScheme.primary)
                    .fillMaxWidth()
                    .padding(4.dp)
            ) {
                val (cartIcon, priceText, confirmButton) = createRefs()
                Surface(
                    modifier = Modifier
                        .padding(4.dp)
                        .shadow(
                            elevation = 2.dp,
                            shape = RoundedCornerShape(roundedCornerSize)
                        )
                        .constrainAs(cartIcon) {
                            top.linkTo(parent.top)
                            bottom.linkTo(parent.bottom)
                            start.linkTo(parent.start)
                        },
                    color = MaterialTheme.colorScheme.surface,
                    shape = RoundedCornerShape(roundedCornerSize)
                ) {
                    Row(
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                        verticalAlignment = Alignment.Bottom
                    ) {
                        IconButton(
                            onClick = {
                                showCartPopup = !showCartPopup
                            },
                            modifier = Modifier.size(36.dp)
                        ) {
                            Icon(
                                imageVector = Icons.Default.ShoppingCart,
                                contentDescription = "购物车"
                            )
                        }
                        Text(
                            text = cart.getTotalQuantity().toString(),
                            maxLines = 1
                        )
                    }
                }
                Text(
                    text = "￥${String.format(Locale.CHINA, "%.2f", cart.totalPrice)}",
                    modifier = Modifier
                        .padding(4.dp)
                        .constrainAs(priceText) {
                            top.linkTo(parent.top)
                            bottom.linkTo(parent.bottom)
                            start.linkTo(cartIcon.end)
                        },
                    maxLines = 1
                )
                IconButton(
                    onClick = {
                        val intent = Intent(context, CheckoutActivity::class.java)
                        intent.putExtra("cart", cart)
                        context.checkoutLauncher.launch(intent)
                    },
                    modifier = Modifier
                        .padding(4.dp)
                        .constrainAs(confirmButton) {
                            top.linkTo(parent.top)
                            bottom.linkTo(parent.bottom)
                            end.linkTo(parent.end)
                        },
                    enabled = cart.totalPrice > 0,
                    colors = IconButtonDefaults.iconButtonColors(
                        containerColor = MaterialTheme.colorScheme.surface
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.Check,
                        contentDescription = "结账"
                    )
                }
            }
            if (showCartPopup) {
                CartPopup(
                    cart = cart,
                    boardWidth = cartBoardWidth,
                    roundedCornerSize = roundedCornerSize,
                    onDismiss = { showCartPopup = false }
                )
            }
        }
    }

    @Composable
    fun CartPopup(
        cart: Cart,
        boardWidth: Int,
        roundedCornerSize: Dp,
        onDismiss: () -> Unit
    ) {
        var showClearConfirmation by remember { mutableStateOf(false) }
        Popup(
            alignment = Alignment.BottomCenter,
            onDismissRequest = onDismiss,
            properties = PopupProperties(
                focusable = true,
                dismissOnBackPress = true,
                dismissOnClickOutside = true
            )
        ) {
            val popupHeight = (LocalConfiguration.current.screenHeightDp) * 0.7f
            val mainBackgroundColor = MaterialTheme.colorScheme.primary
            // 弹窗背景
            Surface(
                modifier = Modifier
                    .width(boardWidth.pxToDp())
                    .height(popupHeight.dp)
                    .clip(RoundedCornerShape(roundedCornerSize))
                    .background(mainBackgroundColor)
                    .padding(16.dp),
            ) {
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f)
                            .background(mainBackgroundColor),
                        userScrollEnabled = true
                    ) {
                        items(cart.items.toList()) { (dish, quantity) ->
                            CartItem(
                                dish = dish,
                                quantity = quantity,
                                onQuantityChange = { newQuantity ->
                                    if (newQuantity > quantity) {
                                        // 增加商品
                                        repeat(newQuantity - quantity) {
                                            cart.addItem(dish)
                                        }
                                    } else if (newQuantity < quantity) {
                                        // 减少商品
                                        repeat(quantity - newQuantity) {
                                            cart.reduceItem(dish)
                                        }
                                    }
                                }
                            )
                        }
                    }
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(1.dp)
                            .background(Color.Black)
                    )
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .background(mainBackgroundColor),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        IconButton(
                            onClick = {
                                showClearConfirmation = true
                            },
                            colors = IconButtonDefaults.iconButtonColors(
                                containerColor = MaterialTheme.colorScheme.surface
                            )
                        ) {
                            Icon(
                                imageVector = Icons.Default.Delete,
                                contentDescription = "清空购物车"
                            )
                        }
                        IconButton(
                            onClick = {
                                onDismiss()
                            },
                            colors = IconButtonDefaults.iconButtonColors(
                                containerColor = MaterialTheme.colorScheme.surface
                            )
                        ) {
                            Icon(
                                imageVector = Icons.Default.Close,
                                contentDescription = "关闭"
                            )
                        }
                    }
                }
            }
        }
        if (showClearConfirmation) {
            ClearCartConfirmationDialog(
                onConfirm = {
                    cart.clear()
                    showClearConfirmation = false
                },
                onDismiss = {
                    showClearConfirmation = false
                }
            )
        }
    }

    @Composable
    fun ClearCartConfirmationDialog(
        onConfirm: () -> Unit,
        onDismiss: () -> Unit
    ) {
        Popup(
            alignment = Alignment.BottomCenter,
            onDismissRequest = onDismiss,
            properties = PopupProperties(
                focusable = true,
                dismissOnBackPress = true,
                dismissOnClickOutside = true
            )
        ) {
            Surface(
                modifier = Modifier
                    .padding(24.dp)
                    .fillMaxWidth(),
                shape = RoundedCornerShape(8.dp),
                color = MaterialTheme.colorScheme.primary
            ) {
                Column(
                    modifier = Modifier.padding(24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "确认清空购物车吗？",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.padding(bottom = 16.dp)
                    )
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceEvenly
                    ) {
                        IconButton(
                            onClick = onDismiss
                        ) {
                            Icon(
                                imageVector = Icons.Default.Close,
                                contentDescription = "取消"
                            )
                        }
                        IconButton(
                            onClick = {
                                onConfirm()
                                onDismiss()
                            }
                        ) {
                            Icon(
                                imageVector = Icons.Default.Check,
                                contentDescription = "确认"
                            )
                        }
                    }
                }
            }
        }
    }

    @Composable
    fun CartItem(
        dish: Dish,
        quantity: Int,
        onQuantityChange: (Int) -> Unit
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 5.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧：名称和额外选项
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 8.dp)
            ) {
                Text(
                    text = dish.name,
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.Bold
                )
                if (!dish.options.isEmpty()) {
                    Text(
                        text = dish.options.joinToString("，"),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            // 右侧：数量操作
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                IconButton(
                    onClick = {
                        onQuantityChange(quantity - 1)
                    }
                ) { Text(text = "-") }
                Text(
                    text = quantity.toString(),
                    modifier = Modifier.padding(horizontal = 8.dp),
                    style = MaterialTheme.typography.bodyLarge
                )
                IconButton(
                    onClick = {
                        onQuantityChange(quantity + 1)
                    }
                ) { Text(text = "+") }
            }
        }
    }

    @Composable
    fun Detail(shop: Shop, modifier: Modifier = Modifier) {
        ConstraintLayout(
            modifier = modifier
                .fillMaxWidth()
                .shadow(
                    elevation = 4.dp,
                    shape = RoundedCornerShape(8.dp)
                )
                .clip(RoundedCornerShape(bottomStart = 8.dp, bottomEnd = 8.dp))
                .background(MaterialTheme.colorScheme.background)
        ) {
            val (image, description) = createRefs()
            SubcomposeAsyncImage(
                model = ImageRequest.Builder(context)
                    .data(shop.imageRes)
                    .crossfade(true)
                    .build(),
                loading = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .background(MaterialTheme.colorScheme.surface),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.image_placeholder),
                            contentDescription = "加载中",
                            tint = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                },
                contentDescription = "店铺图标",
                modifier = Modifier
                    .constrainAs(image) {
                        top.linkTo(parent.top)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                    }
            )
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp)
                    .constrainAs(description) {
                        top.linkTo(image.bottom)
                        start.linkTo(parent.start)
                        end.linkTo(parent.end)
                    }
            ) {
                shop.description?.let {
                    Text(
                        text = it,
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(top = 4.dp)
                    )
                }
            }
        }
    }

    @SuppressLint("ConfigurationScreenWidthHeight")
    @Composable
    fun OrderArea(
        shopId: Int,
        modifier: Modifier = Modifier,
        innerPadding: PaddingValues = PaddingValues(),
        pageScrollState: ScrollState? = null
    ) {
        val areaHeight = LocalConfiguration.current.screenHeightDp.dp - innerPadding.calculateTopPadding()
        val dishes = MockData.dishes.filter { it.shopId == shopId }
        val groupedDishes = dishes.groupBy { it.category }
        val categories = groupedDishes.keys.toList()
        val categoryIndices = remember(groupedDishes) {
            val indices = mutableMapOf<String, Int>()
            groupedDishes.keys.forEachIndexed { index, category ->
                indices[category] = index
            }
            indices
        }
        val scope = rememberCoroutineScope()
        val roundedCornerShape = RoundedCornerShape(8.dp)
        var selectedCategory by remember { mutableStateOf(categories.firstOrNull() ?: "") }
        val dishListState = rememberLazyListState()
        val isPageAtBottom = remember { derivedStateOf { pageScrollState?.value == pageScrollState?.maxValue } }
        var disableAutoCategoryChange by remember { mutableStateOf(false) }
        val nestedScrollConnection = remember(pageScrollState, isPageAtBottom) {
            object : NestedScrollConnection {
                override fun onPreScroll(
                    available: Offset,
                    source: NestedScrollSource
                ): Offset {
                    if (!isPageAtBottom.value && pageScrollState != null && available.y < 0) {
                        val delta = available.y.toInt()
                        val newValue = (pageScrollState.value - delta).coerceIn(0, pageScrollState.maxValue)
                        scope.launch { pageScrollState.scrollTo(newValue) }
                        return Offset(0f, available.y)
                    }
                    return super.onPreScroll(available, source)
                }
            }
        }
        Box(
            modifier = modifier
                .fillMaxWidth()
                .height(areaHeight)
                .padding(10.dp)
                .shadow(
                    elevation = 4.dp,
                    shape = roundedCornerShape
                )
                .clip(roundedCornerShape)
                .background(MaterialTheme.colorScheme.background)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .nestedScroll(nestedScrollConnection)
            ) {
                // 左侧分类标签区域
                CategoryPanel(
                    categories = categories,
                    selectedCategory = selectedCategory
                ) { newCategory ->
                    scope.launch {
                        disableAutoCategoryChange = true
                        if (!isPageAtBottom.value) {
                            pageScrollState?.animateScrollTo(
                                pageScrollState.maxValue,
                                animationSpec = tween(durationMillis = 200)
                            )
                        }
                        if (newCategory != selectedCategory) {
                            selectedCategory = newCategory
                            val index = categoryIndices[newCategory] ?: 0
                            dishListState.animateScrollToItem(index)
                        }
                        disableAutoCategoryChange = false
                    }
                }
                // 右侧餐品列表
                DishList(
                    groupedDishes = groupedDishes,
                    listState = dishListState,
                    onCategoryChanged = { category ->
                        if (!disableAutoCategoryChange && category != selectedCategory) {
                            selectedCategory = category
                        }
                    },
                    modifier = Modifier.weight(1f)
                )
            }
        }
    }

    @Composable
    fun CategoryPanel(
        categories: List<String>,
        selectedCategory: String,
        onCategorySelected: (String) -> Unit
    ) {
        Column(
            modifier = Modifier
                .width(80.dp)
                .fillMaxHeight()
                .background(MaterialTheme.colorScheme.background)
                .verticalScroll(rememberScrollState())
        ) {
            categories.forEach { category ->
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(8.dp)
                        .clip(RoundedCornerShape(4.dp))
                        .background(
                            if (category == selectedCategory)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.surface
                        )
                        .clickable { onCategorySelected(category) }
                        .padding(12.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = category,
                        style = MaterialTheme.typography.bodyMedium,
                        color = if (category == selectedCategory)
                            MaterialTheme.colorScheme.onPrimary
                        else
                            MaterialTheme.colorScheme.onSurface
                    )
                }
            }
        }
    }

    @Composable
    fun DishList(
        groupedDishes: Map<String, List<Dish>>,
        listState: LazyListState,
        onCategoryChanged: (String) -> Unit,
        modifier: Modifier = Modifier
    ) {
        val categories = groupedDishes.keys.toList()
        LaunchedEffect(listState) {
            snapshotFlow {
                Pair(listState.firstVisibleItemIndex, listState.layoutInfo.visibleItemsInfo.size)
            }.collect { (index, visibleItemCount) ->
                val isAtBottom = listState.layoutInfo.totalItemsCount > 0 &&
                        index + visibleItemCount >= listState.layoutInfo.totalItemsCount
                if (isAtBottom && categories.isNotEmpty()) {
                    onCategoryChanged(categories.last())
                } else if (index >= 0 && index < categories.size) {
                    onCategoryChanged(categories[index])
                }
            }
        }
        LazyColumn(
            state = listState,
            modifier = modifier
                .fillMaxHeight()
                .clip(RoundedCornerShape(8.dp))
                .background(MaterialTheme.colorScheme.background)
        ) {
            items(
                items = groupedDishes.toList(),
                key = { it.first }
            ) { (category, dishes) ->
                CategorySection(
                    category = category,
                    dishes = dishes,
                    modifier = if (category == categories.last())
                        Modifier.padding(bottom = 80.dp) else Modifier
                )
            }
        }
    }

    @Composable
    fun CategorySection(
        category: String,
        dishes: List<Dish>,
        modifier: Modifier = Modifier
    ) {
        Column(
            modifier = modifier.fillMaxWidth()
        ) {
            CategoryHeader(category = category)
            dishes.forEach { dish ->
                DishItem(dish = dish)
            }
        }
    }

    @Composable
    fun CategoryHeader(category: String) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.background)
                .padding(8.dp)
        ) {
            Text(
                text = category,
                fontSize = 18.sp,
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.primary
            )
        }
    }

    @Composable
    fun DishItem(dish: Dish) {
        val imageSize = 80.dp
        var showDetailDialog by remember { mutableStateOf(false) }
        if (showDetailDialog) {
            DishDetailDialog(
                dish = dish,
                onDismiss = { showDetailDialog = false },
                onAddToCart = { selectedDish, quantity, options ->
                    val cart = context.cart
                    repeat(quantity) {
                        cart.addItem(selectedDish.copy(options = options))
                    }
                }
            )
        }
        ConstraintLayout (
            modifier = Modifier
                .fillMaxWidth()
                .padding(6.dp)
                .clip(RoundedCornerShape(8.dp))
                .background(MaterialTheme.colorScheme.surface)
                .padding(6.dp)
        ) {
            val (image, text, price, button) = createRefs()
            SubcomposeAsyncImage(
                model = ImageRequest.Builder(context)
                    .data(dish.imageUrl)
                    .crossfade(true)
                    .build(),
                loading = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .background(MaterialTheme.colorScheme.surface),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.image_placeholder),
                            contentDescription = "加载中",
                            tint = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.size(imageSize)
                        )
                    }
                },
                error = {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .aspectRatio(1f)
                            .background(MaterialTheme.colorScheme.surface),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.image_placeholder),
                            contentDescription = "加载中",
                            tint = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.size(imageSize)
                        )
                    }
                },
                contentDescription = "${dish.name}展示图",
                modifier = Modifier
                    .size(imageSize)
                    .clip(RoundedCornerShape(4.dp))
                    .constrainAs(image) {
                        start.linkTo(parent.start)
                        top.linkTo(parent.top)
                        bottom.linkTo(parent.bottom)
                    },
                contentScale = ContentScale.Crop
            )
            Column(
                modifier = Modifier
                    .constrainAs(text) {
                        start.linkTo(image.end, 5.dp)
                        top.linkTo(parent.top)
                    }
            ) {
                Text(
                    text = dish.name,
                    style = MaterialTheme.typography.titleMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Text(
                    text = dish.description,
                    style = MaterialTheme.typography.bodySmall,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }
            Text(
                text = "${dish.basePrice}",
                color = MaterialTheme.colorScheme.secondary,
                style = MaterialTheme.typography.bodySmall,
                modifier = Modifier
                    .constrainAs(price) {
                        start.linkTo(image.end, 5.dp)
                        bottom.linkTo(parent.bottom, 3.dp)
                    }
            )
            val ifNoOptions = dish.options.isEmpty()
            // 添加按钮
            Box(
                modifier = Modifier
                    .height(30.dp)
                    .clip(RoundedCornerShape(4.dp))
                    .constrainAs(button) {
                        end.linkTo(parent.end)
                        bottom.linkTo(parent.bottom)
                    }
                    .clickable(onClick = {
                        if (ifNoOptions) {
                            val cart = context.cart
                            cart.addItem(dish)
                            Log.d("ShopActivity", "cart: $cart")
                        } else {
                            showDetailDialog = true
                        }
                    }),
                contentAlignment = Alignment.Center
            ) {
                if (ifNoOptions) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "添加",
                        modifier = Modifier.size(24.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                } else {
                    Text(
                        text = "选规格",
                        color = MaterialTheme.colorScheme.primary,
                        fontSize = 12.sp,
                        modifier = Modifier
                            .height(24.dp)
                    )
                }
            }
        }
    }

    @Composable
    fun Int.pxToDp(): Dp = with(LocalDensity.current) { this@pxToDp.toDp() }

    suspend fun downloadImageToCache(context: Context, imageUrl: String?): Uri? {
        return withContext(Dispatchers.IO) {
            try {
                if (imageUrl.isNullOrEmpty()) return@withContext null
                // 创建临时文件
                val cacheDir = context.cacheDir
                val imageFile = File(cacheDir, "shared_image_${System.currentTimeMillis()}.jpg")
                // 下载图片
                val url = URL(imageUrl)
                url.openStream().use { input ->
                    FileOutputStream(imageFile).use { output ->
                        input.copyTo(output)
                    }
                }
                // 使用 FileProvider 生成可分享的 URI
                FileProvider.getUriForFile(
                    context,
                    "${context.packageName}.fileprovider",
                    imageFile
                )
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }
        }
    }
}